package main.model.critters.genetics;

import java.util.Random;

import main.model.critters.Critter;
import main.model.critters.CritterFactory;


public class BreedCritters {
	
	public static Critter breed(Critter mother, Critter father){
		if(mother.getSex() != Sex.FEMALE){
			return null;
		}
		if(father.getSex() != Sex.MALE){
			return null;
		}
		Sex sex = CritterFactory.randomSex();
		Chromosome xchromosome = generateChromosome(mother);
		Chromosome ychromosome = generateChromosome(father); 
		Species species = mother.getSpecies();
		Critter offspring = new Critter(xchromosome, ychromosome, 
				mother, father, species, sex);
		return offspring;
	}
	
	
	private static Chromosome generateChromosome(Critter parent){
		Chromosome chromosome = new Chromosome();
		for (GeneType g : GeneType.values()){
			Gene geneX = parent.getXchromosome().getGene(g);
			Gene geneY = parent.getYchromosome().getGene(g);	
			
			if(geneX.getDominance() > geneY.getDominance()){
				chromosome.setGene(g, geneX);
			}else{
				chromosome.setGene(g, geneY);
			}
		}
		int mut = (chromosome.getGene(GeneType.MUTATIONS).getEffect()/2)+1;
		for(int i=0;i<mut;i++){
			mutateChromosome(chromosome);
		}
		return null;
	}
	
	private static void mutateChromosome(Chromosome chromosome){
		Random random = new Random();
		int r = random.nextInt(GeneType.values().length);
		int i = 0;
		for (GeneType g : GeneType.values()){
			if(i == r){
				Gene gene = chromosome.getGene(g);
				
				int area = random.nextInt(3);
				int direction = random.nextInt(2);
				int distance = random.nextInt(4) + random.nextInt(6);
				int x;
				
				if(area == 0){x = gene.getDominance();}
				else{x = gene.getEffect();}
				
				if(direction == 0){x = x + distance;}
				else{x = x - distance;}
				
				if(area == 0){gene.setDominance(x);}
				else{gene.setEffect(x);}
				
				break;
			}else{i++;}
		}
	}
}
